import sys
from linkkit import linkkit
import threading
import traceback
import inspect
import time
import logging

class mqtt:
    
    def __init__(self):
        
                # config log
        __log_format = '%(asctime)s-%(process)d-%(thread)d - %(name)s:%(module)s:%(funcName)s - %(levelname)s - %(message)s'
        logging.basicConfig(format=__log_format)

        self.lk = linkkit.LinkKit(
            host_name="cn-shanghai",
            product_key="a1suZbDlqJn",
            device_name="b1DFpwJYUrEzXrD009qP",
            device_secret="96cd01c88af2c0d7d2b3133d279cedad")
        self.lk.enable_logger(logging.DEBUG)
        
        
        self.lk.on_device_dynamic_register = self.on_device_dynamic_register
        self.lk.on_connect = self.on_connect
        self.lk.on_disconnect = self.on_disconnect
        self.lk.on_topic_message = self.on_topic_message
        self.lk.on_subscribe_topic = self.on_subscribe_topic
        self.lk.on_unsubscribe_topic = self.on_unsubscribe_topic
        self.lk.on_publish_topic = self.on_publish_topic


        self.lk.config_device_info("Eth|03ACDEFF0032|Eth|03ACDEFF0031")
        self.lk.connect_async()
        self.lk.start_worker_loop()
        time.sleep(2)
        
    
    def on_device_dynamic_register(self,rc, value, userdata):
        if rc == 0:
            print("dynamic register device success, value:" + value)
        else:
            print("dynamic register device fail, message:" + value)


    def on_connect(self,session_flag, rc, userdata):
        print("on_connect:%d,rc:%d" % (session_flag, rc))
        pass


    def on_disconnect(self,rc, userdata):
        print("on_disconnect:rc:%d,userdata:" % rc)


    def on_topic_message(self,topic, payload, qos, userdata):
        print("on_topic_message:" + topic + " payload:" + str(payload) + " qos:" + str(qos))
        pass


    def on_subscribe_topic(self,mid, granted_qos, userdata):
        print("on_subscribe_topic mid:%d, granted_qos:%s" %
              (mid, str(','.join('%s' % it for it in granted_qos))))
        pass


    def on_unsubscribe_topic(self,mid, userdata):
        print("on_unsubscribe_topic mid:%d" % mid)
        pass


    def on_publish_topic(self,mid, userdata):
        print("on_publish_topic mid:%d data:%s" % (mid,userdata))

    #upload data to aliyun of iot   
    def upload(self,infodata):
        time.sleep(1)
        rc, mid = self.lk.publish_topic(self.lk.to_full_topic("user/update"), infodata)
        if rc == 0:
            print("publish topic success:%r, mid:%r" % (rc, mid))
        else:
            print("publish topic fail:%d" % rc)